#include "footmarklistview.h"



#include "../../../uitools/vhc/constview4fun.h"
#include "../../../uitools/vhc/constview4id.h"
#include "../../../uitools/vhc/dataupdatecomm.h"


#include "../../page/pagewidgetmini.h"

#include "kemode/ibatis/MyPageParams.h"
#include "kepinyinsimple.h"

#include "it_comm_fm.h"

#include "footmarkeditview.h"

#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QFontDatabase>
#include <QFileInfo>

#include <QModelIndexList>

#include <QDebug>



namespace kepen {
namespace core {


FootmarkListView::FootmarkListView(QWidget *parent
                                   ,KeSysSetting *config
                                   ,QStackedLayout*lay)
    : QWidget{parent}
    ,mapSurface{NULL}
    ,mSysConfig{config}
    ,inputSearch{NULL}
    ,searchAction {NULL}
    ,mTableView{NULL}
    ,mPageWidget{NULL}   
    ,mBtnClose{NULL}
    ,stackedLayout{lay}
    ,dao{NULL}
{
    int fontId = QFontDatabase::addApplicationFont(config->configView()->fileIconFont);
    QString fontName = QFontDatabase::applicationFontFamilies(fontId).at(0);
    QFont fontIcon = QFont(fontName);
    fontIcon.setPointSize(TextSize_IconFont);
    this->fontIconThird = fontIcon;

    initWidget(config);


}

FootmarkListView::~FootmarkListView()
{

}

void FootmarkListView::setDataSource(kepen::core::MapObject* map
                                     ,kepen::kemod::KeFootmarkDao *d)
{
    mapSurface=map;
    dao=d;


}

void FootmarkListView::initWidget(KeSysSetting *conf)
{
    QString nameThiz("FootmarkLayoutBody");
    QString backcolorBody= QString::asprintf("#%08x",Widget_Body_Background);
    QString cssThiz = QString("QWidget#%1{background-color:%2;font-size:%3px;border:0px;border-style:none;}")
                          .arg(nameThiz)
                          .arg(backcolorBody)
                          .arg(TextSize_ToolBar);


    setContentsMargins(0, 0, 0, 0);
    this->setObjectName(nameThiz);
    this->setStyleSheet(cssThiz);



    QVBoxLayout  *verticalLayout = new QVBoxLayout(this);
    verticalLayout->setObjectName("verticalLayoutMain");
    verticalLayout->setSpacing(0);
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    verticalLayout->setAlignment(Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop);




    QWidget *widget_head = buildHead(this,conf);

    verticalLayout->addWidget(widget_head);

    verticalLayout->addSpacerItem(new QSpacerItem(60,4, QSizePolicy::Expanding, QSizePolicy::Policy::Fixed));

    QWidget *widget_search = builSearch(this);

    verticalLayout->addWidget(widget_search);
    verticalLayout->addSpacerItem(new QSpacerItem(60,4, QSizePolicy::Expanding, QSizePolicy::Policy::Fixed));

    QWidget *widget_update = buildUpdate(this);

    verticalLayout->addWidget(widget_update);


    FmTableView *tableView = new FmTableView(this);

    verticalLayout->addWidget(tableView);
    QWidget * pw = buildPageWidget(this);

    verticalLayout->addWidget(pw);

    verticalLayout->addSpacerItem(new QSpacerItem(10,6, QSizePolicy::Expanding, QSizePolicy::Policy::Fixed));

    mTableView = tableView;
    // mPageWidget = pw;
    pw->setVisible(false);

    // 设置双击事件
    connect(tableView, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(onRowDblClicked(const QModelIndex&)));

    connect(tableView, SIGNAL(keyPress4Page(int)),
            this,SLOT(onKeyPress4Page(int)),
            Qt::DirectConnection);

}

bool FootmarkListView::eventFilter(QObject *watched, QEvent *event)
{
    if (inputSearch == watched)
    {
        if (event->type() == QEvent::FocusIn)
        {
            searchAction->setVisible(false);
        }else  if (event->type() == QEvent::FocusOut)
        {
            QString text = inputSearch->text();
            if(text.isEmpty()){
                searchAction->setVisible(true);
            }else
            {
                QString t =text.trimmed();
                if(t.isEmpty())
                {
                    searchAction->setVisible(true);
                }
            }


        }
    }
    return QWidget::eventFilter(watched, event);
}

QPushButton *FootmarkListView::getBtnClose()
{
    return this->mBtnClose;
}

QWidget *FootmarkListView::buildHead(QWidget *parent,KeSysSetting *conf)
{
    int _w = 2 + Height_TileHead, _h = Height_TileHead;
    QFont &_fontIcon=this->fontIconThird;
    QString nameTileHead("tile_footmark");
    QString backcolorHead = QString::asprintf("#%08x",Color_HeadPanel_Background);
    QString cssTileHead = QString("QWidget#%1{background-color:%2;font-size:%3px;border:0px;border-style:none;}")
                              .arg(nameTileHead).arg(backcolorHead).arg(TextSize_ToolBar);

    QString cssBtn = QCSS_IconBtnTileHead();
    QString cssLabel = QString::asprintf("QLabel{background-color:transparent;color:#%08x;border:0px;font-size:%dpx;}"
                                         ,Color_HeadPanel_Label,TextSize_ToolBar);


    QWidget *widget_head = new QWidget(parent);

    widget_head->setObjectName(nameTileHead);
    widget_head->setStyleSheet(cssTileHead);

    QSizePolicy sizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Fixed);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(widget_head->sizePolicy().hasHeightForWidth());
    widget_head->setSizePolicy(sizePolicy);
    widget_head->setFixedHeight(_h);

    QHBoxLayout* headLay = new QHBoxLayout(widget_head);
    headLay->setObjectName("horizonLayoutHead");
    headLay->setSpacing(0);
    headLay->setContentsMargins(0, 0, 0, 0);
    headLay->setAlignment(Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop);



    QPushButton* btnClose = new QPushButton("\ue634",widget_head);
    btnClose->setFont(_fontIcon);
    btnClose->setStyleSheet(cssBtn);
    btnClose->setFixedSize(_w,_h);

    headLay->addWidget(btnClose);

    headLay->addSpacerItem(new QSpacerItem(4,_h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));


    QLabel*headLabel = NULL;
    ushort chFirst = conf->loginFirstName();
    if(chFirst)
    {
        QChar fch(chFirst);
        QString szFirstName(fch);
        QString _t(QStringLiteral(Name_Tab_View));
        QString  szTile = QString("%1    %2").arg(_t,szFirstName);
        headLabel = new QLabel(szTile, widget_head);

    }
    if(NULL == headLabel)
    {
        headLabel = new QLabel(Name_Tab_View, widget_head);
    }


    headLabel->setStyleSheet(cssLabel);
    headLabel->adjustSize();
    // pLabel-> setMinimumSize(pLabel->size().width(), pLabel->size().height());
    // m_pLabel->move(0, (height() - m_pLabel->height()) / 2);
    headLay->addWidget(headLabel);

    headLay->addSpacerItem(new QSpacerItem(4,_h, QSizePolicy::Expanding, QSizePolicy::Policy::Fixed));

    QPushButton* btnData = new QPushButton("\ue71e",widget_head);
    btnData->setFont(_fontIcon);
    btnData->setStyleSheet(cssBtn);
    btnData->setFixedSize(_w,_h);
    headLay->addWidget(btnData);

    QPushButton* btnMore = new QPushButton("\ue85e",widget_head);
    btnMore->setFont(_fontIcon);
    btnMore->setStyleSheet(cssBtn);
    btnMore->setFixedSize(_w,_h);
    headLay->addWidget(btnMore);


    headLay->addSpacerItem(new QSpacerItem(2,_h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));


    // connect(btnClose, &QPushButton::clicked, [&]() {
    //     Q_EMIT onTabViewClosed(this);
    // });
    mBtnClose=btnClose;

    connect(btnData, &QPushButton::clicked, this, &FootmarkListView::onBtnDataSyncClicked);
    connect(btnMore, &QPushButton::clicked, this, &FootmarkListView::onBtnMoreMenuClicked);


    return widget_head;
}

QWidget *FootmarkListView::builSearch(QWidget *parent)
{
    int h = Height_input_Default;
    QString cssInput = QCSS_Input();

    QString nameWidgetThiz(QStringLiteral("widget_search"));

    QString cssWidgetThiz = QString("QWidget#%1{background-color:transparent;font-size:%2px;}")
                                .arg(nameWidgetThiz).arg(TextSize_ToolBar);

    QSizePolicy sizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Fixed);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(parent->sizePolicy().hasHeightForWidth());

    QWidget *widget_Search = new QWidget(parent);

    widget_Search->setObjectName(nameWidgetThiz);
    widget_Search->setStyleSheet(cssWidgetThiz);

    widget_Search->setSizePolicy(sizePolicy);
    widget_Search->setFixedHeight(h);

    QHBoxLayout* horizLay = new QHBoxLayout(widget_Search);
    horizLay->setObjectName("horizonLayoutSearch");
    horizLay->setSpacing(0);
    horizLay->setContentsMargins(0, 0, 0, 0);
    horizLay->setAlignment(Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop);

    QLineEdit * _input= new QLineEdit(widget_Search);


    QAction* _searchAction = new QAction(_input);

    _searchAction->setIcon(QIcon(":/resources/images/icons/zoomin.png"));
    _input->addAction(_searchAction,QLineEdit::LeadingPosition);
    searchAction = _searchAction;



    _input->setSizePolicy(sizePolicy);
    _input->setFixedHeight(h);

    _input->setClearButtonEnabled(true);
    // verticalLayout->addWidget(_input);
    _input->setStyleSheet(cssInput);
    _input->setMaxLength(40);



    connect(_input, SIGNAL(returnPressed()), this, SLOT(onInputSearch()));
    connect(_input, &QLineEdit::textChanged, this, &FootmarkListView::searchTextChanged);

    inputSearch = _input;

    horizLay->addWidget(_input);
    horizLay->addSpacerItem(new QSpacerItem(Pad_Body_Right,h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));


    // _input->setText(QStringLiteral("全"));
    _input->installEventFilter(this);
    _input->setFocusPolicy(Qt::StrongFocus);

    return widget_Search;
}

QWidget *FootmarkListView::buildUpdate(QWidget *parent)
{
    int _w,_h;
    QFont &fontIcon = this->fontIconThird;
    QString namePanelToolBar("widget_update");
    QString backcolorToolBar = QString::asprintf("#%08x",ToolBar_Background);
    QString cssToolBar = QString("QWidget#%1{background-color:%2;font-size:%3px;border:0px;border-style:none;}")
                             .arg(namePanelToolBar).arg(backcolorToolBar).arg(TextSize_ToolBar);

    _w = 2+Height_TileHead;
    _h = Height_TileHead;

    QString cssBtn = QCSS_IconBtnToolBar();

    fontIcon.setPointSize(TextSizeUpdate_IconFont);

    QWidget *widget_bar = new QWidget(parent);

    widget_bar->setObjectName(namePanelToolBar);
    widget_bar->setStyleSheet(cssToolBar);

    QSizePolicy sizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Fixed);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(widget_bar->sizePolicy().hasHeightForWidth());
    widget_bar->setSizePolicy(sizePolicy);
    widget_bar->setFixedHeight(_h);

    QHBoxLayout* horLay = new QHBoxLayout(widget_bar);
    horLay->setObjectName("horizonLayoutUpdate");
    horLay->setSpacing(0);
    horLay->setContentsMargins(0, 0, 0, 0);
    horLay->setAlignment(Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop);

    horLay->addSpacerItem(new QSpacerItem(2,_h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));


    QPushButton* btnAdd = new QPushButton("\ue6dd",widget_bar);
    btnAdd->setFont(fontIcon);
    btnAdd->setStyleSheet(cssBtn);
    btnAdd->setFixedSize(_w,_h);

    horLay->addWidget(btnAdd);

    QPushButton* btnUpdate = new QPushButton("\ue660",widget_bar);
    btnUpdate->setFont(fontIcon);
    btnUpdate->setStyleSheet(cssBtn);
    btnUpdate->setFixedSize(_w,_h);

    horLay->addWidget(btnUpdate);


    horLay->addSpacerItem(new QSpacerItem(12,_h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));

    QPushButton* btnLocate = new QPushButton("\ueab7",widget_bar);
    btnLocate->setFont(fontIcon);
    btnLocate->setStyleSheet(cssBtn);
    btnLocate->setFixedSize(_w,_h);

    horLay->addWidget(btnLocate);

    horLay->addSpacerItem(new QSpacerItem(18,_h, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));

    QPushButton* btnDelete = new QPushButton("\ue776",widget_bar);
    btnDelete->setFont(fontIcon);
    btnDelete->setStyleSheet(cssBtn);
    btnDelete->setFixedSize(_w,_h);

    horLay->addWidget(btnDelete);



    horLay->addSpacerItem(new QSpacerItem(12,_h, QSizePolicy::Expanding, QSizePolicy::Policy::Fixed));

    connect(btnAdd, &QPushButton::clicked,this,&FootmarkListView::onBtnClickedNew);

    connect(btnUpdate, &QPushButton::clicked,this,&FootmarkListView::onBtnClickedUpdate);
    connect(btnDelete, &QPushButton::clicked,this,&FootmarkListView::onBtnClickedDelete);
    connect(btnLocate, &QPushButton::clicked,this,&FootmarkListView::onBtnClickedLocate);

    return widget_bar;
}

QWidget *FootmarkListView::buildPageWidget(QWidget *parent)
{
    int  _h = Height_TileHead;

    QString namePanelToolBar("widget_page");

    QString cssToolBar = QString("QWidget#%1{background-color:transparent;font-size:%3px;border:0px;border-style:none;}")
                             .arg(namePanelToolBar).arg(TextSize_ToolBar);

    QWidget *widget_page = new QWidget(parent);



    widget_page->setObjectName(namePanelToolBar);
    widget_page->setStyleSheet(cssToolBar);

    QSizePolicy sizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Fixed);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(widget_page->sizePolicy().hasHeightForWidth());
    widget_page->setSizePolicy(sizePolicy);
    widget_page->setFixedHeight(_h);

    PageWidgetMini* pa = new PageWidgetMini(widget_page);

    mPageWidget = pa;



    connect(pa, &PageWidgetMini::GotoPageSignals,
            this,&FootmarkListView::gotoPage,
            Qt::DirectConnection);



    return widget_page;
}

void FootmarkListView::clearWhereClause()
{

}

void FootmarkListView::getWhereClause(QVariantMap &andWhere)const
{
    QString txt = inputSearch->text().simplified();

    if(false ==(txt.isEmpty() ||txt.isNull()))
    {
        if(txt.length()>1)
        {
            QString pinyin = KeGetPinyinWrap(txt);
            QStringList vs = pinyin.split(QChar(Pinyin_separator_Default));
            for(auto & it:vs)
            {
                andWhere.insert("pinyin like",it);
            }
        }else
        {
            QString pinyin = KeGetPinyinWrap(txt);
            andWhere.insert("pinyin like",pinyin);
        }

    }


}

void FootmarkListView::locateBy(const QString nodeId)
{
    std::unique_ptr<kepen::kemod::KeFootmark> nodePtr= dao->selectById(nodeId);

    if(nodePtr && false == nodePtr->isNullGeom())
    {
        qint32 level;
        double x,y;
        QString tip = nodePtr ->name;
        x = nodePtr->lng;
        y = nodePtr->lat;
        level = nodePtr->level;

        mapSurface->locateTo(x,y,level,tip);

    }
}





void FootmarkListView::onInputSearch()
{
    gotoPage(1);
}

void FootmarkListView::onBtnDataSyncClicked(){

}

void FootmarkListView::onBtnMoreMenuClicked(){

}


int FootmarkListView::gotoPage(int nToPage)
{
    int thizCount = 0,_curPage;
    int _sizePage,_startIndex,_toPage = nToPage-1;
    PageWidgetMini *pageWidget = mPageWidget;
    kepen::kemod::PageParams pageParam;
    QVariantMap andWhere;
    getWhereClause(andWhere);

    QWidget *_parentW = pageWidget->parentWidget();
    QString orderBy("ORDER BY update_time DESC");



    memset(&pageParam,0,sizeof(pageParam));



    _sizePage = pageWidget->getSizePage();
    _startIndex = _sizePage * _toPage;

    pageParam.sizePage =_sizePage;
    pageParam.start =_startIndex;
    pageParam.andOr = ParamsCondition_Or;
    pageParam.includeDel = Include_DelFlag_No;

    kepen::kemod:: KeFootmark *vs =  dao->selectPageR2(&pageParam,&andWhere,orderBy,&thizCount);
    //  qDebug()  <<__FILE__ <<",Line:"<<__LINE__ << " ,total:" << pageParam.total <<"  sizePage:"<<pageParam.sizePage<<"  vs.size:"<<vs.size();

    if(pageParam.total>pageParam.sizePage)
    {
        _parentW->setVisible(true);

        _curPage = pageWidget->getCurrPage();
        if(nToPage != _curPage)
        {
            pageWidget->setCurrentPage(nToPage);
        }

        pageWidget->SetTotalItem(pageParam.total);


    }else
    {
        _parentW->setVisible(false);
    }




    mTableView->setData(pageParam.start,thizCount,vs);

    dao->releaseArray(vs);

    return thizCount;
}

void FootmarkListView::focusTableView()
{
    if(mTableView)
        mTableView->setFocus(Qt::NoFocusReason);
}

void FootmarkListView::onKeyPress4Page(int key)
{
    if(Qt::Key_Delete == key ||Qt::Key_Backspace == key)
    {
        onBtnClickedDelete();
    }else if(Qt::Key_PageUp == key ||Qt::Key_PageDown == key)
    {
        int p =  mPageWidget->getCurrPage();
        int m = mPageWidget->getMaxPage();

        if(Qt::Key_PageUp == key && p>1)
        {
            --p;
            gotoPage(p);
        }else if(Qt::Key_PageDown == key)
        {

            if(p<m)
            {
                ++p;
                gotoPage(p);

            }
        }


    }
}

void FootmarkListView::onRowDblClicked(const QModelIndex &index)
{

    int row = index.row();
    QAbstractItemModel *model = mTableView->model();
    QModelIndex cell = model->index(row, 0);
    QString nodeId = model->data(cell).toString();
    locateBy(nodeId);
}


void FootmarkListView::onBtnClickedNew()
{
    QStackedLayout *&lay=stackedLayout;
    int count = lay->count();
    if(count>1){

    }
    QWidget *parent=this->parentWidget();
    FootmarkEditView * edit =new FootmarkEditView(parent,NULL,mSysConfig);

    edit->setDataSource(mapSurface,dao);

    lay->addWidget(edit);

    lay->setCurrentIndex(1);

    connect(edit
            ,SIGNAL(stackedWidgetClosed(quint32,QWidget*))
            ,this
            ,SLOT(onStackedClosed(quint32,QWidget*))
            ,Qt::ConnectionType(Qt::DirectConnection| Qt::SingleShotConnection));


}

void FootmarkListView::onBtnClickedUpdate()
{
    QString id = mTableView->getSelectedNodeID();
    if(false == id.isEmpty())
    {
        std::unique_ptr<kepen::kemod::KeFootmark> f =dao->selectById(id);
        QStackedLayout *&lay=stackedLayout;
        QWidget *parent=this->parentWidget();
        FootmarkEditView * edit =new FootmarkEditView(parent,f.get(),mSysConfig);

        edit->setDataSource(mapSurface,dao);

        lay->addWidget(edit);

        lay->setCurrentIndex(1);

        connect(edit
                ,SIGNAL(stackedWidgetClosed(quint32,QWidget*))
                ,this
                ,SLOT(onStackedClosed(quint32,QWidget*))
                ,Qt::ConnectionType(Qt::DirectConnection| Qt::SingleShotConnection));
    }
}



void FootmarkListView::onBtnClickedDelete()
{
    std::vector<kepen::kemod::IdVersionTag> vsID;
    mTableView->getSelectedNodeIDs(vsID);

    if(vsID.size()>0)
    {
        int p =  mPageWidget->getCurrPage();
        dao->deleteMode(&vsID);
        gotoPage(p);
    }
}

void FootmarkListView::onBtnClickedLocate()
{
    QString nodeId = mTableView->getSelectedNodeID();
    if(false == nodeId.isEmpty())
    {

        locateBy(nodeId);
    }
}

void FootmarkListView::onStackedClosed(quint32 flag,QWidget*widget)
{
    stackedLayout->removeWidget(widget);

    QString ss = QString::number(flag,16);

    if(Changed_Record == (Changed_Record & flag))
    {
        if(New_Record == (New_Record & flag))
        {
            clearWhereClause();
            // onGotoPage(1);//@See searchTextChanged
        }else if(Update_Record == (Update_Record & flag))
        {
            FootmarkEditView* editView = dynamic_cast<FootmarkEditView*>(widget);
            kepen::kemod::KeFootmark *f = editView->getData();

            mTableView->refreshBy(f);
        }
    }


    widget->deleteLater();
}



void FootmarkListView::searchTextChanged(const QString &text)
{
    if(text.isEmpty()||text.isNull())
    {
        // qDebug()  <<__FILE__ <<",Line:"<<__LINE__ <<"empty";
        gotoPage(1);
    }
}



}
}

